package patterndesign.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description
 * @Date 2021/9/18
 * @Created by Jonathan
 * 这种需要产生固定数量对象的模式就叫做有上限的多例模式，
 * 它是单例模式的一种扩展，采用有上限的多例模式，
 */
public class Emperor {
    private static int maxNumOfEmperor = 2; // 表示有两个皇帝
    private static List<String> nameList = new ArrayList<>();
    private static List<Emperor> emperorList = new ArrayList<>();
    // 当前皇帝序列号
    private static int countNumOfEmperor = 0;

    // 产生所有的对象
    static {
        for (int i = 0; i < maxNumOfEmperor; i++) {
            emperorList.add(new Emperor("第" + (i + 1) + "个皇帝"));
        }
    }

    private Emperor() {
        // 世俗和道德的约束，目的就是不产生第二个皇帝
    }

    private Emperor(String name) {
        nameList.add(name);
    }

    public static Emperor getInstance() {
        Random r = new Random();
        countNumOfEmperor = r.nextInt(maxNumOfEmperor);
        return emperorList.get(countNumOfEmperor);
    }

    public static void say() {
        System.out.println(nameList.get(countNumOfEmperor));
    }

}
